package br.edu.com1263.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.StaleObjectStateException;

import br.edu.com1263.dao.Connection;

public class HibernateSessionRequestFilter implements Filter {
	private EntityManager em;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			em.getTransaction().begin();

			chain.doFilter(request, response);

			em.getTransaction().commit();

		} catch (StaleObjectStateException staleEx) {
			throw staleEx;
		} catch (Throwable ex) {
			ex.printStackTrace();
			try {
				if (em.getTransaction().isActive()) {
					em.getTransaction().rollback();
				}
			} catch (Throwable rbEx) {
			}
			throw new ServletException(ex);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		em = Connection.getInstance().getManager();
	}

	public void destroy() {
		em.close();
	}
}
